package com.ruoyi.common.utils;

import com.ruoyi.project.param.paeaParaSystem.domain.PaeaParaSystem;
import com.ruoyi.project.system.user.domain.User;
import net.northking.paea.SdiPaeaArcStatus;
import net.northking.workitempool.cluster.client.QueueFilter;
import net.northking.workitempool.cluster.client.ResultWrapper;
import net.northking.workitempool.cluster.client.WorkItemPoolClient;

/**
 * 用workItemPool进行任务获取
 * @author skynus
 *
 */
public class TaskQueue {
	public static TaskQueue instance = new TaskQueue();

	private TaskQueue() {
		loadQueueServerInfo();
	}


	public static TaskQueue getInstance() {
		return instance;
	}

	/**
	 * 队列进行任务获取
	 * @param status
	 * @param user
	 * @return
	 */
	public ResultWrapper obtainWorkItem(int status, User user) {
		final WorkItemPoolClient client = new WorkItemPoolClient(queueServerIp, queueServerPort,
				WorkItemPoolClient.WORK_ITEM_POOL_CLUSTER);
		QueueFilter[] queueFilters;
		String expressionOrg = "workItem.getInputOrgCode()==\"" + user.getUserId() + "\""
				+ " || workItem.getAuditOrgCode()==\"" + user.getDeptId() + "\"";
		String queueName = "paea_" + status;
		QueueFilter queueFilterOrg = new QueueFilter(queueName, expressionOrg);
		QueueFilter queueFilter = new QueueFilter(queueName, null);
		if (status == SdiPaeaArcStatus.待手工补录400.getValue()) {
			if (ignoreOrg) {//&& isRootOrgUser(user)
				queueFilters = new QueueFilter[] {
						new QueueFilter("paea_" + SdiPaeaArcStatus.待重新补录790.getValue(), null), queueFilter };
			} else {
				queueFilters = new QueueFilter[] {
						new QueueFilter("paea_" + SdiPaeaArcStatus.待重新补录790.getValue(), expressionOrg), queueFilterOrg };
			}
		} else {
			if (ignoreOrg) {//&& isRootOrgUser(user)
				queueFilters = new QueueFilter[] { queueFilter };
			} else {
				queueFilters = new QueueFilter[] { queueFilterOrg };
			}
		}

		return client.obtainWorkItems(queueFilters, user.getUserId(), 1);

	}

//	private boolean isRootOrgUser(User user) {
//		String orgCode = CommonParaTool.getSmOrganByCode(CommonParaTool.getSmOrganByCode(user.getOrgId()).getParentOrgId()).getOrgCode();
//		return user.getDeptId().equals(orgCode) ? true : false;
//	}

	/**
	 * 加载任务池地址信息
	 */
	private void loadQueueServerInfo() {
		PaeaParaSystem para = CommonParaTool.getPaeaParaSystemByOrgCode("task_queue");
		queueServerIp = para.getFileHttpIp();
		queueServerPort = para.getFileHttpPort();
		ignoreOrg = "true".equalsIgnoreCase(para.getReserved7());
	}
	private boolean ignoreOrg;
	private String queueServerIp = null;
	private int queueServerPort = 0;
}
